define(function(require) {
	// var $ = require("jquery");
	var fn = require("$UI/ls_common/fn");
	var justep = require("$UI/system/lib/justep");
	require("cordova!com.justep.cordova.plugin.barcodescanner");// 调用为：justep.barcodeScanner；

	var Model = function() {
		this.callParent();
		this.ID = 0;
		this.PackingRatio = 0;
	};

	Model.prototype.ReScan_ButtonClick = function(event) {
		this.QrScan();
	};
	Model.prototype.Return_ButtonClick = function(event) {
		fn.cat_x5_data(this.comp("BarCode"));
		this.getParent().comp("BarCode_Data").clear();
		this.getParent().comp("BarCode_Data").loadData(this.comp("BarCode").toJson());
		fn.cat_x5_data(this.getParent().comp("BarCode_Data"));
		this.getParent().comp("contents1").to("TaskDetailsCntent");
	};

	Model.prototype.DeleteScanCode_i9Click = function(event) {
		console.log("DeleteScanCode_i9Click");
		console.log(event);
		console.log(event.bindingContext.$object);
		this.comp("BarCode").directDeleteMode = true; // 这行必须加，否则只做一个标记而已。
		this.comp("BarCode").deleteData(event.bindingContext.$object);
		fn.cat_x5_data(this.comp("BarCode"));
		this.ReCount(this.ID);
		$(this.getElementByXid("ReScan_Button")).show();
	};
	Model.prototype.AddCodeToShaoMiaoData = function(Code, Type) {
		// TODO:只解析code=xxxxx中的数字部分
		var row = this.comp("BarCode").find([ 'code' ], [ Code ]);
		if (row.length !== 0) {
			console.log("数据已经存在");
			console.log(Code);
			justep.Util.hint("这个条码已经扫描过，请核对产品后再继续操作");
			return;
		}
		this.comp("BarCode").newData({
			"index" : 0,
			"defaultValues" : [ {
				"Type" : Type,
				"code" : Code,
				"ID" : this.ID,
			} ]
		});

		var count = this.comp("BarCode").find([ 'ID' ], [ this.ID ]);
		this.ReCount(this.ID);
		// this.comp("FaHuoLieBiaoData").setValue("ScanCount", count.length);

		var PrdCount = this.comp("Status").val("Total_Count");
		console.log("继续扫描？" + PrdCount + ">" + count.length);
		if (PrdCount > count.length) {
			var that = this;
			setTimeout(function() {
				that.QrScan();
			}, 500); // 如果没有扫满，继续调用扫描
		} else if (PrdCount == count.length) {
			justep.Util.hint("条码扫描完毕，请核对。");
			$(this.getElementByXid("ReScan_Button")).hide();
		}
	};
	Model.prototype.QrScan_scanok = function(res) {
		window.scanstatus = "scanok";
		console.log("QrScan_scanok()");
		console.log(res);
		var data = {};
		data.username = window.app.username;
		data.password = window.app.password;

		data.Code = res.text.substr(res.text.length - 16, 16);
		// 1小袋，0大袋
		if (res.text.length === 16) {
			data.Type = "0";
		} else {
			var CodeUrl = res.text.substr(0, res.text.length - 16);
			if (CodeUrl === window.app.LargebagUrl)
				data.Type = "0";
			if (CodeUrl === window.app.PouchUrl)
				data.Type = "1";
		}
		console.log("data.Type=", data.Type);

		if (1) {
			this.AddCodeToShaoMiaoData(data.Code, data.Type); // 调试用
			return;
		}

		var self = this;
		var api_url = window.app.base_url + window.app.SelCodeBatch;
		$.ajax({
			type : "POST",
			url : require.toUrl(api_url),
			data : {
				'data' : JSON.stringify(data)
			},
			dataType : 'json',
			success : function(res) {
				console.log(res);
				// this.AddCodeToShaoMiaoData(res);
				if (res.length < 1) {
					justep.Util.hint("仓库中不存在这个条码/二维码。");
				}
				if (res.length == 1) {
					self.AddCodeToShaoMiaoData(data.Code, data.Type);
				}
				if (res.length > 0) {
					justep.Util.hint("这个条码/二维码,已经重复了。");
				}
				return;
			},
			error : function(err) {
				console.log(err);
				return;
			}
		});
	};
	Model.prototype.QrScan_cancelled = function(res) {
		console.log("QrScan_cancelled()");
		window.scanstatus = "cancelled";
	};
	Model.prototype.QrScan_err = function(err) {
		console.log("QrScan_err()");
		window.scanstatus = "err";
	};
	Model.prototype.QrScan = function() {
		console.log("QrScan()");
		window.scanstatus = "scaning";
		if (justep.Browser.isX5App) {
			var self = this;
			console.log(justep.barcodeScanner);
			justep.barcodeScanner.scan(function(res) {
				var cancelled = res.cancelled;
				if (cancelled) {
					self.QrScan_cancelled(res);
				} else {
					self.QrScan_scanok(res);
				}
			}, function(ee) {
				self.QrScan_err(ee);
			});
		} else {
			var tmpdata = [ "www.hnliben.top:5008/sx/q.aspx?code=1234544444444406", "www.hnliben.top:5008/sx/d.aspx?code=4444444444444407", "www.hnliben.top:5008/sx/q.aspx?code=4444444444444408",
					"4444444444444409", "4444444444444410", "4444444444444411", "www.hnliben.top:5008/sx/q.aspx?code=4444444444444412", "www.hnliben.top:5008/sx/q.aspx?code=4444444444444413",
					"www.hnliben.top:5008/sx/d.aspx?code=0911902289578781", "www.hnliben.top:5008/sx/q.aspx?code=4444444444444406" ];
			var tmpstr = tmpdata[Math.floor(Math.random() * 10)];
			this.QrScan_scanok({
				text : tmpstr
			});
		}
	};

	Model.prototype.ReCount = function(ID) {
		var count = 0;
		var self = this;
//		console.log(ID);
		this.comp('BarCode').count(function(ev) {
//			console.log(ev.source.getValue("ID"));
			if (ID == ev.source.getValue("ID", ev.row)) {
				var v = ev.source.getValue('Type', ev.row);
				if (parseInt(v) === 0)
					count += self.PackingRatio;
				if (parseInt(v) === 1)
					count += 1;
			}
		});
		this.comp("Status").setValue("Current_Count", count);

	};
	Model.prototype.modelParamsReceive = function(event) {
		console.log("modelParamsRecive()");
		this.comp("BarCode").clear();
		console.log(event.params);
		if (event.params === undefined || event.params.SubID === undefined) {
			justep.Util.hint("子订单号获取失败，出错了。");
		} else {
			console.log("parent model");
			this.ID = event.params.SubID;
			this.PackingRatio = parseInt(event.params.PackingRatio.substr(2));
			console.log("包装比例为:", this.PackingRatio);
			this.comp("BarCode").clear();
			this.comp("BarCode").loadData(this.getParent().comp("BarCode_Data").toJson());
			this.comp("list2").filter = " $row.val(\"ID\") ==  " + event.params.SubID;
			this.comp("list2").refresh();
			this.ReCount(this.ID);
			this.comp("Status").setValue("Total_Count", event.params.PrdCount);
			$(this.getElementByXid("ReScan_Button")).show();
		}

	};

	Model.prototype.modelLoad = function(event) {
		console.log("modelLoad()");
	};

	Model.prototype.InputBtnClick = function(event) {
		this.comp("windowDialog1").open();
	};

	return Model;
});